package iNotes;

import iNotes.assist.DataPool;
import iNotes.assist.Utils;
import org.apache.commons.text.StringEscapeUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.*;

@WebServlet(name = "AddItem", value = "/AddItem")
public class AddItem extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        return;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if(!Utils.checkToken(session,request)){
            response.getWriter().write("CSRF attack detected!");
            return;
        }
        request.setCharacterEncoding("utf-8");
        String newContent = StringEscapeUtils.escapeHtml4(request.getParameter("content"));
        newContent = URLEncoder.encode(newContent, "utf-8");
        int uid = (int) session.getAttribute("uid");


        Connection connection = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement2 = null;
        ResultSet resultSet = null;
        try {
            connection = DataPool.ds.getConnection();
            preparedStatement1 = connection.prepareStatement("insert into note values(NULL,?,now());", Statement.RETURN_GENERATED_KEYS);
            preparedStatement1.setString(1, newContent);
            preparedStatement1.executeUpdate();
            resultSet = preparedStatement1.getGeneratedKeys();
            int key = -1;
            if(resultSet.next()){
                key = resultSet.getInt(1);
            }
            preparedStatement2 = connection.prepareStatement("insert into user_note values(?,?);");
            preparedStatement2.setInt(1,uid);
            preparedStatement2.setInt(2,key);
            preparedStatement2.execute();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            Utils.close(connection,resultSet,preparedStatement1,preparedStatement2);
        }
        response.sendRedirect("notes.jsp");
    }
}
